package com.innerchic.weqiuqiu.assembly;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.RemoteInput;

import com.innerchic.weqiuqiu.R;
import com.innerchic.weqiuqiu.bean.MessageBean;
import com.innerchic.weqiuqiu.bean.MessageReply;
import com.innerchic.weqiuqiu.bean.old.MessageMade;
import com.innerchic.weqiuqiu.emoji.EmojiView;
import com.innerchic.weqiuqiu.emoji.Expression;
import com.innerchic.weqiuqiu.emoji.OnClickEmojiListener;

/**
 * ================================================
 * 作    者：贾恒飞 >>> 17515250730@163.com
 * 项    目：wedudu
 * 日    期：2022/1/17 17:53
 * 包    名：com.innerchic.weqiuqiu.assembly
 * 描    述：发送消息的Dialog
 * Create by zFox from AndroidStudio4.2
 * ================================================
 */
public class SendMessageDialog extends Dialog {

    private final EditText contentText;

    private final TextView toUserText;

    private final EmojiView emojiView;

    private final TextView closeDialog;

    private final ImageView expressionBtn;

    private final TextView sendBtn;

    public void getContentFocus() {
        if (contentText == null) {
            return;
        }
        contentText.requestFocus();
    }

    public interface OnSendOver {
        void onSend(MessageBean bean, String sendText);
    }

    private OnSendOver sendOver;

    public void setSendOver(OnSendOver sendOver) {
        this.sendOver = sendOver;
    }

    public SendMessageDialog(@NonNull Context context) {
        super(context, R.style.BottomDialog);
        View inflate = LayoutInflater.from(context).inflate(R.layout.dialog_send_message, null);
        contentText = inflate.findViewById(R.id.contentText);
        toUserText = inflate.findViewById(R.id.toUserText);
        emojiView = inflate.findViewById(R.id.emojiView);
        closeDialog = inflate.findViewById(R.id.closeDialog);
        expressionBtn = inflate.findViewById(R.id.expressionBtn);
        sendBtn = inflate.findViewById(R.id.sendBtn);

        initContent();

        closeDialog.setOnClickListener(v -> {
            clearStatus();
            cancel();
        });

        setOnDismissListener(dialog -> {
            clearStatus();
        });

        expressionBtn.setOnClickListener(v -> {
            emojiView.setVisibility((emojiView.getVisibility() == View.GONE) ? View.VISIBLE : View.GONE);
        });

        sendBtn.setOnClickListener(v -> {
            try {
                String content = contentText.getText().toString();
                if (content.trim().equals("")) {
                    Toast.makeText(getContext(), "请输入内容后回复.", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (messageBean == null) {
                    Toast.makeText(getContext(), "请重新选择要回复的对象.", Toast.LENGTH_SHORT).show();
                    return;
                }
                MessageReply messageReply = messageBean.getMessageReply();
                if (messageReply == null || messageReply.getReplyPendingIntent() == null) {
                    Toast.makeText(getContext(), "该消息不可被回复.", Toast.LENGTH_SHORT).show();
                    return;
                }
                sendMessage(messageReply, content);
                //关闭相关
                clearStatus();
                cancel();
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getContext(), "消息回复异常,请打开后回复.", Toast.LENGTH_SHORT).show();
            }
        });

        emojiView.setEmojiListener(new OnClickEmojiListener() {
            @Override
            public void onClick(Expression expression, int pos) {
                Editable text = contentText.getText();
                if (text == null || "".equals(text.toString())) {
                    contentText.append("[" + expression.getName() + "]");
                    return;
                }
                int index = contentText.getSelectionStart();
                text.insert(index, "[" + expression.getName() + "]");
            }

            @Override
            public void onLongClick(Expression expression, int pos) {
                Toast.makeText(getContext(), expression.getName(), Toast.LENGTH_SHORT).show();
            }
        });

        //将布局设置给Dialog
        setContentView(inflate);
        setWindowsParams();
    }

    private void clearStatus() {
        toUserText.setText("回复给:");
        emojiView.setVisibility(View.GONE);
        contentText.setText("");
        messageBean = null;
    }

    private void setWindowsParams() {
        if (getWindow() != null) {
            //获取当前Activity所在的窗体
            WindowManager.LayoutParams params = getWindow().getAttributes();
            // 设置宽高为match_parent，不要去算出来屏幕宽高再赋值哦，因为有些
            //有虚拟按键的手机上计算出来的高度不一定准确，所以dialog不会全屏
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            getWindow().setAttributes(params);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                getWindow().setType((WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY));
            } else {
                getWindow().setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
            }
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            //设置Dialog从窗体底部弹出
            getWindow().setGravity(Gravity.BOTTOM);
        }
    }

    private MessageBean messageBean;

    public void setMessageBean(MessageBean messageBean) {
        this.messageBean = messageBean;
        initContent();
    }

    public void initContent() {
        if (messageBean == null) {
            String errorMessage = "回复给: <font color='red'>没有相对的接受者信息</font>";
            toUserText.setText(Html.fromHtml(errorMessage));
        } else {
            String content = "回复给: " + messageBean.getContent();
            toUserText.setText(content);
        }
    }

    private void sendMessage(MessageReply data, String message) {
        Intent localIntent = new Intent();
        Bundle resultBundle = new Bundle();
        resultBundle.putString(data.getKey(), message);
        RemoteInput.addResultsToIntent(new RemoteInput[]{new RemoteInput.Builder(data.getKey()).build()}, localIntent, resultBundle);
        try {
            data.getReplyPendingIntent().send(getContext(), 0, localIntent);
            //回调
            if (sendOver == null) {
                return;
            }
            sendOver.onSend(messageBean, message);
        } catch (Exception e) {
            Toast.makeText(getContext(), "该消息异常无法回复.", Toast.LENGTH_SHORT).show();
        }
    }
}
